#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib2

HEADER = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
           'Accept-Encoding': 'gzip,deflate,sdch',
           'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4',
           'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36'
        }


class Downloader():
    def __init__(self, cookie = None):
        self.data = None
        self.url = ''
        self.cokie = cookie
    def getFileNameByUlr(self):
        pass
    
    def getTrueUrl(self):
        return self.url
    
    def saveToLocal(self, data, file_path):
        fp = open(file_path)
        fp.write(data)
        fp.close()
        
    def downLoadFile(self, url):
        opener = urllib2.build_opener()
        data = None
        try:
            request = urllib2.Request(url = url, headers = HEADER)
            response = opener.open(request, timeout = 10)
            print response.url
            print response.getcode()
            self.url = response.geturl()
            if response.info().get('Content-Encoding') == 'gzip':
                from StringIO import StringIO
                import gzip
                buf = StringIO( response.read())
                f = gzip.GzipFile(fileobj=buf)
                data = f.read()
            else:
                data = response.read()
        except Exception, e:
            print url,e
        return data
        pass
    
if __name__ == '__main__':
    pass

